const { createApp } = Vue;

createApp({
    data() {
        return {
            categories: [],
            currentPage: 1,
            pageSize: 10,
            totalCategories: 0,
            searchKey: '',
            form: {
                id: null,
                name: '',
                description: '',
                is_active: '1',
                sort_order: 0
            },
            categoryModal: null,
            updating: null // 记录正在更新状态的分类ID
        }
    },
    computed: {
        totalPages() {
            return Math.ceil(this.totalCategories / this.pageSize);
        },
        pageNumbers() {
            const pages = [];
            let start = Math.max(1, this.currentPage - 2);
            let end = Math.min(this.totalPages, start + 4);
            
            if (end - start < 4) {
                start = Math.max(1, end - 4);
            }
            
            for (let i = start; i <= end; i++) {
                pages.push(i);
            }
            return pages;
        }
    },
    methods: {
        async loadCategories() {
            try {
                const response = await fetch(`/api/admin/categories?page=${this.currentPage}&size=${this.pageSize}&search=${this.searchKey}`);
                const data = await response.json();
                
                if (data.code === 200) {
                    this.categories = data.data;
                    this.totalCategories = data.total;
                } else {
                    throw new Error(data.msg || '获取分类列表失败');
                }
            } catch (error) {
                console.error('加载分类数据失败:', error);
                Swal.fire({
                    icon: 'error',
                    title: '加载失败',
                    text: error.message || '请刷新重试'
                });
            }
        },
        changePage(page) {
            if (page < 1 || page > this.totalPages) return;
            this.currentPage = page;
            this.loadCategories();
        },
        searchCategories() {
            this.currentPage = 1;
            this.loadCategories();
        },
        handleAdd() {
            this.form = {
                id: null,
                name: '',
                description: '',
                is_active: '1',
                sort_order: 0
            };
            this.categoryModal.show();
        },
        handleEdit(category) {
            this.form = {
                id: category.id,
                name: category.name,
                description: category.description || '',
                is_active: category.is_active,
                sort_order: category.sort_order
            };
            this.categoryModal.show();
        },
        async handleDelete(category) {
            const result = await Swal.fire({
                title: '确认删除',
                text: `确定要删除分类"${category.name}"吗？此操作不可恢复！`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: '确定删除',
                cancelButtonText: '取消',
                confirmButtonColor: '#dc3545'
            });

            if (result.isConfirmed) {
                try {
                    const response = await fetch(`/api/admin/category/${category.id}`, {
                        method: 'DELETE'
                    });
                    const data = await response.json();
                    
                    if (data.code === 200) {
                        Swal.fire({
                            icon: 'success',
                            title: '删除成功',
                            showConfirmButton: false,
                            timer: 1500
                        });
                        this.loadCategories();
                    } else {
                        throw new Error(data.msg || '删除失败');
                    }
                } catch (error) {
                    console.error('删除分类失败:', error);
                    Swal.fire({
                        icon: 'error',
                        title: '删除失败',
                        text: error.message || '请重试'
                    });
                }
            }
        },
        async saveCategory() {
            if (!this.form.name?.trim()) {
                Swal.fire({
                    icon: 'warning',
                    title: '请填写分类名称'
                });
                return;
            }

            try {
                const url = this.form.id ? 
                    `/api/admin/category/update?id=${this.form.id}` : 
                    '/api/admin/category/create';

                const response = await fetch(url, {
                    method: this.form.id ? 'PUT' : 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(this.form)
                });

                const data = await response.json();
                
                if (data.code === 200) {
                    this.categoryModal.hide();
                    Swal.fire({
                        icon: 'success',
                        title: this.form.id ? '更新成功' : '添加成功',
                        showConfirmButton: false,
                        timer: 1500
                    });
                    this.loadCategories();
                } else {
                    throw new Error(data.msg || (this.form.id ? '更新失败' : '添加失败'));
                }
            } catch (error) {
                console.error('保存分类失败:', error);
                Swal.fire({
                    icon: 'error',
                    title: '保存失败',
                    text: error.message || '请重试'
                });
            }
        },
        async toggleCategoryStatus(category) {
            try {
                this.updating = category.id;
                const newStatus = category.is_active == 1 ? '0' : '1';
                
                const response = await fetch(`/api/admin/category/${category.id}/status`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        is_active: newStatus
                    })
                });

                const data = await response.json();
                
                if (data.code === 200) {
                    category.is_active = newStatus;
                    const statusText = newStatus == '1' ? '启用' : '禁用';
                    Swal.fire({
                        icon: 'success',
                        title: `分类已${statusText}`,
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 1500
                    });
                } else {
                    throw new Error(data.msg || '操作失败');
                }
            } catch (error) {
                console.error('切换分类状态失败:', error);
                Swal.fire({
                    icon: 'error',
                    title: '操作失败',
                    text: error.message || '请重试'
                });
                // 恢复原状态
                category.is_active = category.is_active == 1 ? '0' : '1';
            } finally {
                this.updating = null;
            }
        },
        async handleSortChange(category) {
            try {
                const response = await fetch(`/api/admin/category/${category.id}/sort`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        sort_order: category.sort_order
                    })
                });

                const data = await response.json();
                
                if (data.code === 200) {
                    Swal.fire({
                        icon: 'success',
                        title: '排序已更新',
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 1500
                    });
                } else {
                    throw new Error(data.msg || '更新排序失败');
                }
            } catch (error) {
                console.error('更新排序失败:', error);
                Swal.fire({
                    icon: 'error',
                    title: '更新失败',
                    text: error.message || '请重试'
                });
                // 恢复原值
                this.loadCategories();
            }
        }
    },
    mounted() {
        this.loadCategories();
        // 初始化模态框
        this.$nextTick(() => {
            const modalElement = document.getElementById('categoryModal');
            if (modalElement) {
                this.categoryModal = new bootstrap.Modal(modalElement);
            }
        });
    }
}).mount('#categoryApp'); 